﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;

namespace AccountControl
{
    public partial class AccountControlWindow : Form
    {
        private static string AccountsXMLFileName = "Accounts.XML";
        private static string ArchiveXMLFileName = "Archive.XML";
        private static string HistoryXMLFileName = "History.XML";
        private static string BanksXMLFileName = "Banks.XML";
        private static string CurrencyXMLFileName = "Currency.XML";
        private static string OwnersXMLFileName = "Owners.XML";
        
        private int AccountsInfoGridViewLastVisitedIndex;
        private Color AccountsInfoGridViewLastModifiedRowBackcolor;

        private DataTable Accounts;
        private DataTable Archive;
        private DataTable History;
        private List<string> Banks;
        private List<string> CurrencyData;
        private List<string> Owners;

        private int SoonPaymentRemainingDays = 100;
        private Color ColorForSoonPaymentRemainingDays = Color.LightPink;
        private Color ColorForOrdinaryDeposit = Color.LightGreen;
        private Color ColorForPastDeposit = Color.Red;

        public AccountControlWindow()
        {
            InitializeComponent();

            LoadAccountsData();
            LoadArchiveData();
            LoadHistoryData();
            LoadBanksData();
            LoadCurrencyData();
            LoadOwnersData();
        }

        private void LoadAccountsData()
        {
            Accounts = DataLoader.LoadAccountsDataFromXML(AccountsXMLFileName);
            BindingSource accountsInfoSource = new BindingSource();
            accountsInfoSource.DataSource = Accounts;
            AccountsInfoGridView.DataSource = accountsInfoSource;
            Accounts.DefaultView.Sort = "Падеж ASC";
        }

        private void LoadArchiveData()
        {
            Archive = DataLoader.LoadArchiveDataFromXML(ArchiveXMLFileName);
            BindingSource archiveInfoSource = new BindingSource();
            archiveInfoSource.DataSource = Archive;
            ArchiveInfoGridView.DataSource = archiveInfoSource;
            Archive.DefaultView.Sort = "Архивиран ASC";
        }

        private void LoadHistoryData()
        {
            History = DataLoader.LoadHistoryDataFromXML(HistoryXMLFileName);
            BindingSource historyInfoSource = new BindingSource();
            historyInfoSource.DataSource = History;
            HistoryInfoGridView.DataSource = historyInfoSource;
        }

        private void LoadBanksData()
        {
            Banks = DataLoader.LoadBanksDataFromXML(BanksXMLFileName);

            BindingSource newAccountBanksSource = new BindingSource();
            newAccountBanksSource.DataSource = Banks;
            NewAccountBankBox.DataSource = newAccountBanksSource;

            BindingSource editAccountBanksSource = new BindingSource();
            editAccountBanksSource.DataSource = Banks;
            EditAccountBankBox.DataSource = editAccountBanksSource;

            BindingSource resourceDataBanksListSource = new BindingSource();
            resourceDataBanksListSource.DataSource = Banks;
            ResourceDataBanksList.DataSource = resourceDataBanksListSource;
        }

        private void LoadCurrencyData()
        {
            CurrencyData = DataLoader.LoadCurrencyDataFromXML(CurrencyXMLFileName);

            BindingSource newAccountCurrencySource = new BindingSource();
            newAccountCurrencySource.DataSource = CurrencyData;
            NewAccountCurrencyBox.DataSource = newAccountCurrencySource;

            BindingSource editAccountCurrencySource = new BindingSource();
            editAccountCurrencySource.DataSource = CurrencyData;
            EditAccountCurrencyBox.DataSource = editAccountCurrencySource;

            BindingSource resourceDataCurrencyListSource = new BindingSource();
            resourceDataCurrencyListSource.DataSource = CurrencyData;
            ResourceDataCurrencyList.DataSource = resourceDataCurrencyListSource;
        }

        private void LoadOwnersData()
        {
            Owners = DataLoader.LoadOwnersDataFromXML(OwnersXMLFileName);

            BindingSource newAccountOwnersSource = new BindingSource();
            newAccountOwnersSource.DataSource = Owners;
            NewAccountOwnerBox.DataSource = newAccountOwnersSource;

            BindingSource editAccountOwnersSource = new BindingSource();
            editAccountOwnersSource.DataSource = Owners;
            EditAccountOwnerBox.DataSource = editAccountOwnersSource;

            BindingSource resourceDataOwnersListSource = new BindingSource();
            resourceDataOwnersListSource.DataSource = Owners;
            ResourceDataOwnersList.DataSource = resourceDataOwnersListSource;

            BindingSource reportInfoOwnersSource = new BindingSource();
            List<string> ownersDataForReport = new List<string>();
            ownersDataForReport.Add("--- Всички собственици ---");
            ownersDataForReport.AddRange(Owners);
            reportInfoOwnersSource.DataSource = ownersDataForReport;
            ReportInfoOwnerBox.DataSource = reportInfoOwnersSource;
        }

        private bool ValidateAccountData(ComboBox bankSource, TextBox amountSource, TextBox periodSource, ComboBox ownerSource)
        {
            string intPattern = @"\A([1-9][0-9]{0,8})\Z";
            if (bankSource.Text == "")
            {
                MessageBox.Show("Некоректни данни!\nМоля посочете валидно име за банка!", "Внимание!");
                return false;
            }
            if (!Regex.IsMatch(amountSource.Text, intPattern))
            {
                MessageBox.Show("Некоректни данни!\nМоля посочете валидна сума за депозит!", "Внимание!");
                return false;
            }
            if (!Regex.IsMatch(periodSource.Text, intPattern))
            {
                MessageBox.Show("Некоректни данни!\nМоля посочете валиден период за депозит (в месеци)!", "Внимание!");
                return false;
            }
            if (ownerSource.Text == "")
            {
                MessageBox.Show("Некоректни данни!\nМоля посочете валидно име за собственик!", "Внимание!");
                return false;
            }

            return true;
        }

        private bool ValidateAndShowPaymentDate(DateTimePicker creationDateSorce, TextBox periodSorce, TextBox paymentDateDestination)
        {
            if (periodSorce.Text != "")
            {
                try
                {
                    int period = int.Parse(periodSorce.Text);
                    DateTime paymentDate = creationDateSorce.Value.AddMonths(period);
                    paymentDateDestination.Text = paymentDate.ToString("dd/MM/yyyy");
                    return true;
                }
                catch (Exception)
                {
                    MessageBox.Show("Некоректни данни!\nМоля въведете валиден период за депозит (в месеци)!", "Внимание!");
                    return false;
                }
            }
            else 
            {
                return false;
            }
        }

        private void HighlightAccounts() 
        {
            foreach(DataGridViewRow row in AccountsInfoGridView.Rows)
            {
                DateTime accountPaymentDate = BulgarianDate.Parse(row.Cells["Падеж"].Value.ToString()).Date;
                int daysLeftUntilPaymentDate = accountPaymentDate.Subtract(DateTime.Now).Days;

                if (daysLeftUntilPaymentDate >= 0 && daysLeftUntilPaymentDate <= SoonPaymentRemainingDays)
                {
                    row.DefaultCellStyle.BackColor = ColorForSoonPaymentRemainingDays;
                }
                else 
                {
                    if (daysLeftUntilPaymentDate >= 0)
                    {
                        row.DefaultCellStyle.BackColor = ColorForOrdinaryDeposit;
                    }
                    else 
                    {
                        row.DefaultCellStyle.BackColor = ColorForPastDeposit;
                    }
                }
            }
            
            DataGridView.HitTestInfo findCellPos;
            Point mousePos = AccountsInfoGridView.PointToClient(MousePosition);
            findCellPos = AccountsInfoGridView.HitTest(mousePos.X, mousePos.Y);
            int rowIndex = findCellPos.RowIndex;
            int colIndex = findCellPos.ColumnIndex;
            if (rowIndex >= 0 && colIndex >= 0)
            {
                AccountsInfoGridViewLastModifiedRowBackcolor =
                    AccountsInfoGridView.Rows[rowIndex].DefaultCellStyle.BackColor;
            }
        }

        private Panel CreateReportPanelForOwner(string name)
        {
            Panel reportPanel = new Panel();
            reportPanel.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;

            DataTable reportTable = new DataTable();
            Dictionary<string, DataRow> bankData = new Dictionary<string, DataRow>();
            Dictionary<string, bool> isCurrencyUsed = new Dictionary<string, bool>();

            reportTable.Columns.Add("Банка");
            reportTable.Columns["Банка"].DataType = typeof(string);
            foreach (string currency in CurrencyData)
            {
                reportTable.Columns.Add(currency);
                reportTable.Columns[currency].DataType = typeof(int);

                isCurrencyUsed.Add(currency, false);
            }

            DataRow ownerCompleteAmountReport = reportTable.NewRow();
            ownerCompleteAmountReport["Банка"] = "--- ОБЩО ---";
            foreach (string currency in CurrencyData)
            {
                ownerCompleteAmountReport[currency] = 0;
            }

            foreach (DataRow account in Accounts.Rows) 
            {
                if ((string)account["Собственик"] == name) 
                {
                    string bank = (string)account["Банка"];
                    Amount amount = (Amount)account["Сума"];

                    if (!CurrencyData.Contains(amount.Currency)) 
                    {
                        continue;
                    }

                    if (!bankData.ContainsKey(bank))
                    {
                        DataRow bankRow = reportTable.NewRow();
                        bankRow["Банка"] = bank;
                        foreach (string currency in CurrencyData)
                        {
                            bankRow[currency] = 0;
                        }
                        bankData.Add(bank, bankRow);
                    }

                    DataRow currentRow = bankData[bank];
                    int currentAmount = (int)currentRow[amount.Currency];
                    int currentCompleteAmount = (int)ownerCompleteAmountReport[amount.Currency];
                    currentAmount += amount.Value;
                    currentCompleteAmount += amount.Value;
                    currentRow[amount.Currency] = currentAmount;
                    ownerCompleteAmountReport[amount.Currency] = currentCompleteAmount;

                    isCurrencyUsed[amount.Currency] = true;
                }
            }

            foreach (string bank in Banks)
            {
                if (bankData.ContainsKey(bank)) 
                {
                    reportTable.Rows.Add(bankData[bank]);
                }
            }

            if (reportTable.Rows.Count != 0) 
            {
                reportTable.Rows.Add(ownerCompleteAmountReport);
            }

            foreach (string currency in CurrencyData)
            {
                if (!isCurrencyUsed[currency])
                {
                    reportTable.Columns.Remove(currency);
                }
            }

            Label reportLabel = new Label();
            reportLabel.Text = "Отчет за " + name + " :";
            reportLabel.Location = new Point(0, 0);
            reportLabel.Size = new Size(ReportInfoPanel.Width, 20);
            reportPanel.Controls.Add(reportLabel);

            if (reportTable.Rows.Count == 0)
            {
                reportPanel.Size = new Size(ReportInfoPanel.Width, 45);

                Label noBanksUsed = new Label();
                noBanksUsed.Text = "Няма намерени депозити!";
                noBanksUsed.Location = new Point(10, 25);
                noBanksUsed.Size = new Size(ReportInfoPanel.Width, 20);
                reportPanel.Controls.Add(noBanksUsed);
            }
            else
            {
                reportPanel.Size = new Size(ReportInfoPanel.Width, 175);

                DataGridView reportDataGridView = new DataGridView();
                reportDataGridView.Location = new Point(0, 25);
                reportDataGridView.Size = new Size(ReportInfoPanel.Width, 150);
                reportDataGridView.AllowUserToAddRows = false;
                reportDataGridView.AllowUserToDeleteRows = false;
                reportDataGridView.AllowUserToResizeColumns = false;
                reportDataGridView.AllowUserToResizeRows = false;
                reportDataGridView.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
                reportDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
                reportDataGridView.BackgroundColor = Color.SteelBlue;
                reportDataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
                reportDataGridView.EditMode = DataGridViewEditMode.EditProgrammatically;
                reportDataGridView.MultiSelect = false;
                reportDataGridView.RowHeadersVisible = false;
                reportDataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                reportDataGridView.ShowCellToolTips = false;

                BindingSource reportSource = new BindingSource();
                reportSource.DataSource = reportTable;
                reportDataGridView.DataSource = reportSource;

                reportDataGridView.Paint += (sender, e) =>
                {
                    DataGridView dataGridView = ((DataGridView)sender);
                    foreach (DataGridViewRow row in dataGridView.Rows) 
                    {
                        if ((string)row.Cells["Банка"].Value == "--- ОБЩО ---") 
                        {
                            row.DefaultCellStyle.Font =
                            new Font("Microsoft Sans Serif", 8f, FontStyle.Bold);
                        }
                    }
                };

                reportPanel.Controls.Add(reportDataGridView);
            }

            return reportPanel;
        }

        private void AddHistoryEntry(string entryEvent, BulgarianDate date, string bank, 
            Amount amount, int period, BulgarianDate paymentDate, string name) 
        {
            DataRow dataRow = History.NewRow();
            dataRow["No."] = History.Rows.Count + 1;
            dataRow["Дата и час"] = new BulgarianDate(DateTime.Now, true);
            dataRow["Събитие"] = entryEvent;
            dataRow["Дата"] = date;
            dataRow["Банка"] = bank;
            dataRow["Сума"] = amount;
            dataRow["Период"] = period;
            dataRow["Падеж"] = paymentDate;
            dataRow["Собственик"] = name;

            History.Rows.Add(dataRow);
            DataSaver.SaveHistoryInXMLFile(HistoryXMLFileName, History);
        }

        private void AccountsInformationGridView_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                DataGridView.HitTestInfo findCellPos;
                findCellPos = AccountsInfoGridView.HitTest(e.X, e.Y);
                if (findCellPos.RowIndex >= 0 && findCellPos.ColumnIndex >= 0)
                {
                    if (AccountsInfoGridViewLastVisitedIndex != findCellPos.RowIndex + 1)
                    {
                        AccountsInfoGridViewLastVisitedIndex = findCellPos.RowIndex + 1;

                        DataGridViewRow currentRow = AccountsInfoGridView.Rows[findCellPos.RowIndex];
                        string accountOwner = currentRow.Cells["Собственик"].Value.ToString();
                        string accountBank = currentRow.Cells["Банка"].Value.ToString();
                        string accountAmount = currentRow.Cells["Сума"].Value.ToString();
                        string accountPaymentDate = currentRow.Cells["Падеж"].Value.ToString();
                        TimeSpan DifferenceToPayment = BulgarianDate.Parse(accountPaymentDate).Date.Subtract(DateTime.Now);
                        int daysDifferenceToPayment = DifferenceToPayment.Days;
                        string imageFileName = "cash.JPG";

                        this.AccountInfoPictureBox.Image = Image.FromFile(imageFileName, true);
                        AccountInfoOwnerDynamicLabel.Text = accountOwner;
                        AccountInfoBankDynamicLabel.Text = accountBank;
                        AccountInfoAmountDynamicLabel.Text = accountAmount;
                        AccountInfoPaymentDynamicLabel.Text = accountPaymentDate;

                        if (daysDifferenceToPayment > SoonPaymentRemainingDays)
                        {
                            AccountInfoPaymentCountdownDynamicLabel.Text = "падеж след " + daysDifferenceToPayment + " ден(а)";
                            AccountInfoPaymentCountdownDynamicLabel.ForeColor = Color.DarkGreen;
                        }
                        else
                        {
                            if (daysDifferenceToPayment >= 0)
                            {
                                AccountInfoPaymentCountdownDynamicLabel.Text = "падеж след " + daysDifferenceToPayment + " ден(а)";
                                AccountInfoPaymentCountdownDynamicLabel.ForeColor = Color.DarkRed;
                            }
                            else
                            {
                                AccountInfoPaymentCountdownDynamicLabel.Text = "изтекъл";
                                AccountInfoPaymentCountdownDynamicLabel.ForeColor = Color.DarkRed;
                            }
                        }
                    }

                    Point cursorPosition = this.PointToClient(new Point(Cursor.Position.X, Cursor.Position.Y));
                    int horisontalPosition =
                        AccountsInfoTabControl.Location.X + AccountsInfoTabControl.Width >
                        cursorPosition.X + AccountInfoPanel.Width + 10 ?
                        cursorPosition.X + 10 : cursorPosition.X - AccountInfoPanel.Width - 10;
                    int verticalPosition =
                        AccountsInfoTabControl.Location.Y + AccountsInfoTabControl.Height >
                        cursorPosition.Y + AccountInfoPanel.Height + 10 ?
                        cursorPosition.Y + 10 : cursorPosition.Y - AccountInfoPanel.Height - 10;
                    this.AccountInfoPanel.Location = new Point(horisontalPosition, verticalPosition);

                    this.AccountInfoPanel.Visible = true;
                    AccountInfoPanel.Refresh();
                }
                else
                {
                    this.AccountInfoPanel.Visible = false;
                    AccountsInfoGridViewLastVisitedIndex = 0;
                }
            }
            catch(Exception)
            {
                this.AccountInfoPanel.Visible = false;
                AccountsInfoGridViewLastVisitedIndex = 0;
                return;
            }
        }

        private void NewAccoundAddBtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (ValidateAccountData(NewAccountBankBox, NewAccountAmountBox, NewAccountPeriodBox, NewAccountOwnerBox))
                {
                    BulgarianDate newDepositCreationDate = new BulgarianDate(NewAccountCreationDateBox.Value);
                    string newDepositBank = NewAccountBankBox.SelectedItem.ToString();
                    Amount newDepositAmount = new Amount(int.Parse(NewAccountAmountBox.Text), NewAccountCurrencyBox.Text);
                    int newDepositPeriod = int.Parse(NewAccountPeriodBox.Text);
                    BulgarianDate newDepositPaymentDate = BulgarianDate.Parse(NewAccountPaymentDateBox.Text);
                    string newDepositOwner = NewAccountOwnerBox.Text;

                    DialogResult isUserAgree = 
                        MessageBox.Show(
                                    "Добавям депозит!\n\nДанни за новият депозит:\n\n" +
                                    "\tДата на създаване:   " + newDepositCreationDate + "\n" +
                                    "\tБанка:   " + newDepositBank + "\n" +
                                    "\tСума:   " + newDepositAmount + "\n" +
                                    "\tПериод:   " + newDepositPeriod + " месец(а)" + "\n" +
                                    "\tПадеж:   " + newDepositPaymentDate + "\n" +
                                    "\tСобственик:   " + newDepositOwner,
                                    "Успешно добавяне!", MessageBoxButtons.OKCancel);

                    if (isUserAgree == DialogResult.OK)
                    {
                        DataRow dataRow = Accounts.NewRow();
                        dataRow["No."] = Accounts.Rows.Count + 1;
                        dataRow["Дата"] = newDepositCreationDate;
                        dataRow["Банка"] = newDepositBank;
                        dataRow["Сума"] = newDepositAmount;
                        dataRow["Период"] = newDepositPeriod;
                        dataRow["Падеж"] = newDepositPaymentDate;
                        dataRow["Собственик"] = newDepositOwner;

                        Accounts.Rows.Add(dataRow);
                        DataSaver.SaveAccountsInXMLFile(AccountsXMLFileName, Accounts);
                        HighlightAccounts();

                        AddHistoryEntry("добавен депозит", newDepositCreationDate, newDepositBank,
                        newDepositAmount, newDepositPeriod, newDepositPaymentDate, newDepositOwner);
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Некоректни или невалидни данни!\nМоля проверете въведените стойности!", "Внимание!");
            }
        }

        private void AccountsInformationGridView_MouseLeave(object sender, EventArgs e)
        {
            this.AccountInfoPanel.Visible = false;
        }

        private void NewAccountCreationDateBox_ValueChanged(object sender, EventArgs e)
        {
            ValidateAndShowPaymentDate(NewAccountCreationDateBox, NewAccountPeriodBox, NewAccountPaymentDateBox);
        }

        private void NewAccountPeriodBox_Leave(object sender, EventArgs e)
        {
            ValidateAndShowPaymentDate(NewAccountCreationDateBox, NewAccountPeriodBox, NewAccountPaymentDateBox);
        }

        private void ResourceDataBanksAddBtn_Click(object sender, EventArgs e)
        {
            if (ResourceDataBanksAddInput.Text != "")
            {
                Banks.Add(ResourceDataBanksAddInput.Text);
                DataSaver.SaveBanksDataInXMLFile(BanksXMLFileName, Banks);
                LoadBanksData();
            }
            else 
            {
                MessageBox.Show("Некоректни или невалидни данни!\nМоля проверете въведеното име за банка!", "Внимание!");
            }
        }

        private void ResourceDataCurrencyAddBtn_Click(object sender, EventArgs e)
        {
            if (ResourceDataCurrencyAddInput.Text != "")
            {
                CurrencyData.Add(ResourceDataCurrencyAddInput.Text);
                DataSaver.SaveCurrencyDataInXMLFile(CurrencyXMLFileName, CurrencyData);
                LoadCurrencyData();
            }
            else
            {
                MessageBox.Show("Некоректни или невалидни данни!\nМоля проверете въведеното име за валута!", "Внимание!");
            }
        }

        private void ResourceDataOwnersAddBtn_Click(object sender, EventArgs e)
        {
            if (ResourceDataOwnersAddInput.Text != "")
            {
                Owners.Add(ResourceDataOwnersAddInput.Text);
                DataSaver.SaveOwnersDataInXMLFile(OwnersXMLFileName, Owners);
                LoadOwnersData();
            }
            else
            {
                MessageBox.Show("Некоректни или невалидни данни!\nМоля проверете въведеното име за собственик!", "Внимание!");
            }
        }

        private void AccountControlWindow_Load(object sender, EventArgs e)
        {
            Accounts.DefaultView.Sort = "Падеж ASC";
            Archive.DefaultView.Sort = "Архивиран DESC";
            History.DefaultView.Sort = "Дата и час DESC";
            HighlightAccounts();
        }

        private void AccountsInformationGridView_Sorted(object sender, EventArgs e)
        {
            HighlightAccounts();
        }

        private void AccountsInformationGridView_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                DataGridViewRow row = AccountsInfoGridView.Rows[e.RowIndex];
                AccountsInfoGridViewLastModifiedRowBackcolor = row.DefaultCellStyle.BackColor;
                row.DefaultCellStyle.ForeColor = Color.White;
                row.DefaultCellStyle.BackColor = Color.Black;
            }
        }

        private void AccountsInformationGridView_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                DataGridViewRow row = AccountsInfoGridView.Rows[e.RowIndex];
                row.DefaultCellStyle.ForeColor = Color.Black;
                row.DefaultCellStyle.BackColor = AccountsInfoGridViewLastModifiedRowBackcolor;
            }
        }

        private void AccountsInformationGridView_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                e.ContextMenuStrip = AccountsInfoContextMenuStrip;
                HighlightAccounts();
                DataGridViewRow row = AccountsInfoGridView.Rows[e.RowIndex];
                row.Selected = true;
            }
        }

        private void AccountsInfoMoveToArchive_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Премествам депозит в архив!", "Потвърждение", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                int selectedRowIndex = (int)(AccountsInfoGridView.SelectedRows[0].Cells["No."].Value) - 1;
                DataRow row = Accounts.Rows[selectedRowIndex];

                DataRow newArchiveRecord = Archive.NewRow();
                newArchiveRecord["No."] = Archive.Rows.Count + 1;
                newArchiveRecord["Дата"] = row["Дата"];
                newArchiveRecord["Банка"] = row["Банка"];
                newArchiveRecord["Сума"] = row["Сума"];
                newArchiveRecord["Период"] = row["Период"];
                newArchiveRecord["Падеж"] = row["Падеж"];
                newArchiveRecord["Собственик"] = row["Собственик"];
                newArchiveRecord["Архивиран"] = new BulgarianDate(DateTime.Now);
                
                AddHistoryEntry("местене в архив", (BulgarianDate)row["Дата"], (string)row["Банка"],
                    (Amount)row["Сума"], (int)row["Период"], (BulgarianDate)row["Падеж"], (string)row["Собственик"]);

                Archive.Rows.Add(newArchiveRecord);
                Accounts.Rows.Remove(row);

                DataSaver.SaveArchiveInXMLFile(ArchiveXMLFileName, Archive);
                DataSaver.SaveAccountsInXMLFile(AccountsXMLFileName, Accounts);

                LoadAccountsData(); // Prevent wrong rowIndex taken
                HighlightAccounts();
            }
        }

        private void EditAccountPeriodBox_Leave(object sender, EventArgs e)
        {
            ValidateAndShowPaymentDate(EditAccountCreationDateBox, EditAccountPeriodBox, EditAccountPaymentDateBox);
        }

        private void EditAccountAddBtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (ValidateAccountData(EditAccountBankBox, EditAccountAmountBox, EditAccountPeriodBox, EditAccountOwnerBox))
                {
                    BulgarianDate editDepositCreationDate = new BulgarianDate(EditAccountCreationDateBox.Value);
                    string editDepositBank = EditAccountBankBox.SelectedItem.ToString();
                    Amount editDepositAmount = new Amount(int.Parse(EditAccountAmountBox.Text), EditAccountCurrencyBox.Text);
                    int editDepositPeriod = int.Parse(EditAccountPeriodBox.Text);
                    BulgarianDate editDepositPaymentDate = BulgarianDate.Parse(EditAccountPaymentDateBox.Text);
                    string editDepositOwner = EditAccountOwnerBox.Text;

                    DialogResult isUserAgree =
                        MessageBox.Show(
                                    "Редактирам депозит!\n\nДанни за новият депозит:\n\n" +
                                    "\tДата на създаване:   " + editDepositCreationDate + "\n" +
                                    "\tБанка:   " + editDepositBank + "\n" +
                                    "\tСума:   " + editDepositAmount + "\n" +
                                    "\tПериод:   " + editDepositPeriod + " месец(а)" + "\n" +
                                    "\tПадеж:   " + editDepositPaymentDate + "\n" +
                                    "\tСобственик:   " + editDepositOwner,
                                    "Успешно редактиране!", MessageBoxButtons.OKCancel);

                    if (isUserAgree == DialogResult.OK)
                    {
                        DataRow dataRow = Accounts.NewRow();
                        dataRow["No."] = Accounts.Rows.Count + 1;
                        dataRow["Дата"] = editDepositCreationDate;
                        dataRow["Банка"] = editDepositBank;
                        dataRow["Сума"] = editDepositAmount;
                        dataRow["Период"] = editDepositPeriod;
                        dataRow["Падеж"] = editDepositPaymentDate;
                        dataRow["Собственик"] = editDepositOwner;

                        Accounts.Rows.Add(dataRow);

                        DataSaver.SaveAccountsInXMLFile(AccountsXMLFileName, Accounts);
                        HighlightAccounts();

                        AddHistoryEntry("редактиран депозит", editDepositCreationDate, editDepositBank,
                        editDepositAmount, editDepositPeriod, editDepositPaymentDate, editDepositOwner);
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Некоректни или невалидни данни!\nМоля проверете въведените стойности!", "Внимание!");
            }
        }

        private void AccountsInfoEdit_Click(object sender, EventArgs e)
        {
            //fix
            int selectedRowForEditIndex = (int)(AccountsInfoGridView.SelectedRows[0].Cells["No."].Value) - 1;
            DataRow row = Accounts.Rows[selectedRowForEditIndex];
            //MessageBox.Show(selectedRowForEditIndex.ToString() + " " + row["No."].ToString());
            
            EditAccountCreationDateBox.Value = ((BulgarianDate)row["Дата"]).Date;
            EditAccountBankBox.Text = (string)row["Банка"];
            EditAccountAmountBox.Text = ((Amount)row["Сума"]).Value.ToString();
            EditAccountCurrencyBox.Text = ((Amount)row["Сума"]).Currency;
            EditAccountPeriodBox.Text = row["Период"].ToString();
            EditAccountPaymentDateBox.Text = ((BulgarianDate)row["Падеж"]).ToString();
            EditAccountOwnerBox.Text = (string)row["Собственик"];

            AddHistoryEntry("започната редакция", (BulgarianDate)row["Дата"], (string)row["Банка"],
                    (Amount)row["Сума"], (int)row["Период"], (BulgarianDate)row["Падеж"], (string)row["Собственик"]);

            Accounts.Rows.Remove(row);
            DataSaver.SaveAccountsInXMLFile(AccountsXMLFileName, Accounts);
            LoadAccountsData();
            HighlightAccounts();
        }

        private void ReportInfoOwnerBox_DropDownClosed(object sender, EventArgs e)
        {
            ReportInfoPanel.Controls.Clear();
            int vpos = 0;

            if (ReportInfoOwnerBox.SelectedIndex == 0)
            {
                foreach (string owner in Owners)
                {
                    Panel currentReport = CreateReportPanelForOwner(owner);

                    ReportInfoPanel.Controls.Add(currentReport);
                    currentReport.Location = new Point(0, vpos);
                    vpos += currentReport.Height + 10;
                }
            }
            else 
            {
                Panel currentReport = CreateReportPanelForOwner(ReportInfoOwnerBox.Text);

                ReportInfoPanel.Controls.Add(currentReport);
                currentReport.Location = new Point(0, vpos);
            }
        }
    }
}